package com.panda.expand;


import com.google.common.base.Joiner;
import com.panda.pojo.Context;
import com.panda.pojo.Element;
import com.panda.utils.Finder;
import lombok.Getter;
import lombok.Setter;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
    元素功能的拓展

    该扩展会自动从调用点搜集需要的参数

 */
@Setter
@Getter
public class Extend implements BodyParser {

    private String name;

    private String body;

    //动态的参数
    private String params;

    //需要自动搜集的参数
    private String collect;

    private Pattern pattern;

    public Extend(String name, Set<String> params, Set<String> collect, String body) {
        this.name = name;
        this.body = body;

        this.params = Joiner.on(",").join(params);

        this.collect = "," + Joiner.on(",").join(collect);


        pattern = Pattern.compile("\\.[\n ]*" + name + "[\n ]*(?=\\()");

    }

    @Override
    public String parseBody(Context context, Element element, String s) {

        Matcher matcher = pattern.matcher(s);

        String t = s;

        while (matcher.find()) {

            int param = Finder.findParam(s.toCharArray(), matcher.end());

            //携带原始参数的调用
            String o = s.substring(matcher.start(), param);

            //将参数插入
            String to = o.substring(0, o.length() - 1) + collect + o.charAt(o.length() - 1);

            //将搜集后的参数替换
            t = t.replace(s.substring(matcher.start(), param), to);

        }

        return t;

    }

    @Override
    public String toString() {

        return " $.fn.extend({'" + name + "': function (" + params + collect + ") {" + body + "}});\n";
    }

}
